﻿using System;
using System.Windows;
using System.Windows.Threading;

namespace WebsiteLoadTool
{
    /// <summary>
    /// Main Application
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Constructs a new instance of App.
        /// </summary>
        public App()
        {
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                AppDomain.CurrentDomain.UnhandledException += AppCurrentDomainUnhandledException;
                DispatcherUnhandledException += AppDispatcherUnhandledException;
            }
        }

        /// <summary>
        /// Occurs when an exception is not handled.
        /// </summary>
        private void AppCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // Are we not on the main UI thread?
            if (!Application.Current.Dispatcher.CheckAccess())
            {
                // Unhandled exceptions on worker threads will halt the application. We want to
                // use our global exception handler(s), so dispatch or "forward" to the UI thread.
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action<Exception>(WorkerThreadException), e.ExceptionObject as Exception);
            }
            else
            {
                throw e.ExceptionObject as Exception;  // Already on UI thread; just rethrow the exception to global handlers
            }

        }

        /// <summary>
        /// Called for retrowing exception on UI thread.
        /// </summary>
        private static void WorkerThreadException(Exception ex)
        {
            throw ex;
        }

        /// <summary>
        /// Occurs when an exception is thrown by the application but not handled.
        /// </summary>
        private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString(), e.Exception.Message, MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
